package com.glory.brepda.activity.material;

import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.glory.brepda.R;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.entity.PickingEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.MyUtils;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.OnClick;

public class MaterialRlfOutActivity extends BaseActivity {


    private LinearLayout llMain;

    // 领料单申请数量
    private TextView tvMainQty;

    // 领料单主键，主要用来区别领料单
    private Long appointmentObjectRrn;

    // 领料单已经发料了的数量
    private TextView tvReserved6;

    // 扫描发料的物料批次号
    private FreeUI_ClearEditText etMLotID;

    // 待发料集合
    private MLotRlfOutAdapter mLotOutAdapter;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_material_rlf_out;
    }

    @Override
    protected void initView() {

        llMain = findViewById(R.id.llMain);

        TextView tvTitle = findViewById(R.id.tvTitle);
        TextView tvAppointmentMaterialSpec = findViewById(R.id.tvAppointmentMaterialSpec);
        tvMainQty = findViewById(R.id.tvMainQty);
        TextView tvEqpId = findViewById(R.id.tvEqpId);
        // 设备位置号显示框
        TextView tvEqpLocation = findViewById(R.id.tvEqpLocation);
        TextView tvReserved5 = findViewById(R.id.tvReserved5);
        tvReserved6 = findViewById(R.id.tvReserved6);
        etMLotID = findViewById(R.id.etMLotID);

        // 设置副标题
        tvTitle.setText("框架领料单发料");

        // 25/4/23 901713 修改：扫入的二维码不进行大写转换，一些框架的二维码含了小写的字母："na"，把它也转成大写会对后面流程有影响。
        initEditNotToUpperCase(etMLotID, this::verifyAndAddMLot);

        // 为各个文本框赋值
        Bundle bundle = getIntent().getExtras();
        // 领料单指定的物料规格
        tvAppointmentMaterialSpec.setText(bundle.getString("materialSpec"));
        // 领料单申请数量
        tvMainQty.setText(bundle.getString("mainQty"));
        // 领料设备号
        tvEqpId.setText(bundle.getString("eqpId"));
        // 领料设备位置号
        tvEqpLocation.setText(bundle.getString("eqpLocation"));
        // 指定供应商
        tvReserved5.setText(bundle.getString("reserved5"));
        // 领料单已发料的数量
        tvReserved6.setText(bundle.getString("reserved6"));
        // 领料单主键，该页面最重要的变量，是后台识别该领料单的唯一变量
        appointmentObjectRrn = bundle.getLong("objectRrn");

        RecyclerView rvMLotOut = findViewById(R.id.rvMLotOut);
        initRecyclerView(rvMLotOut, MaterialRlfOutActivity.this);

        // 适配器定义，点击事件定义
        mLotOutAdapter = new MLotRlfOutAdapter(null);
        mLotOutAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        mLotOutAdapter.isFirstOnly(true);
        rvMLotOut.setAdapter(mLotOutAdapter);

    }

    /**
     * 发送请求到后台验证该框架是否符合领料单要求的规格，添加到待发料区域里
     * @param mLotId 扫描需要发料的框架二维码
     */
    private void verifyAndAddMLot(String mLotId) {

        if (StringUtils.isEmpty(mLotId) || appointmentObjectRrn == null) {
            showToast("信息填写未完成，请检查",false);
            return;
        }

        // 禁止扫描重复批号
        if (mLotOutAdapter.getData().contains(mLotId)) {
            showToast("禁止扫描重复批号", false);
            return;
        }

        // 检查是否有扫描多物料批数量，即控制 扫描发料框的数量 + 已经发料了的数量 == 领料单的数量，不可发多
        try {
            // 已发料的数量 + 待发料的数量
            int sumQty = Integer.parseInt(String.valueOf(tvReserved6.getText())) + mLotOutAdapter.getData().size();
            if (sumQty == Integer.parseInt(String.valueOf(tvMainQty.getText()))) {
                showConfirmDialog("已发料数量和待发料数量和已与领料数量相等，禁止继续扫物料批号");
                return;
            }
        } catch (NumberFormatException e) {
            showToast("解析领料单数量失败", false);
            return;
        }

        postPickingData("VERIFY_APPOINTMENT_MLOT");
    }

    @Override
    protected void initData() {

    }

    /**
     * 客制化主标题显示，本次主要重写左边按钮即返回按钮
     * @return 新的主标题
     */
    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("框架发料");

        // 点击返回按钮，结束掉当前窗口
        freeUI_titleView.setLeftListener(v -> finish());

        return new FreeUI_AddViewEntity("header", llMain);
    }

    @OnClick({R.id.tvBaseSubmit})
    public void onViewClicked(View view) {
        if (view.getId() == R.id.tvBaseSubmit) {
            // 检查是否有领料单信息，是否有扫描物料批
            if (appointmentObjectRrn == null || mLotOutAdapter.getData().size() == 0) {
                showToast("信息填写未完成，请检查", false);
                return;
            }

            FreeApi_DialogUtils.getConfirmAndCancelDialog(this, "确定要发料?", () -> postPickingData("APPOINTMENT_MLOT_OUT"), ()->{}).show(getSupportFragmentManager(),"MaterialRlfOut");
        }
    }

    /**
     * 与后台接口进行交互
     * @param actionType 动作类型：VERIFY_APPOINTMENT_MLOT：检查扫描物料批号是否和领料单相符，APPOINTMENT_MLOT_OUT：物料批、领料单发料
     */
    private void postPickingData(String actionType) {
        // 接口返回使用 PickingEntity 接住
        FreeUI_EntityCallBack<BaseResponseBean<PickingEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<PickingEntity>>
                (new TypeToken<BaseResponseBean<PickingEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<PickingEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {

                    // 解析接口返回领料单数据，根据领料单剩余数量来判断该领料单是否已经完成，若完成，可以关闭该页面
                    ArrayList<PickingEntity> pickingEntityList = response.body().getResponse().getBody().getPickingEntityList();

                    // 接口设计是会返回领料单信息的，如没有获取到，证明有系统问题，这里需要维护人员介入
                    if (pickingEntityList.size() == 0) {
                        showConfirmDialog("系统错误，请联系管理员");
                    }

                    PickingEntity pickingEntity = pickingEntityList.get(0);
                    // 领料单的状态为已完成，对已经完成了的领料单
                    if (StringUtils.equals(pickingEntity.getSTATUS(), "OUT")) {
                        showToast("领料单已完成", true);
                        // 等待提示信息弹出，然后退出该页面
                        new Handler().postDelayed(() -> finish(), 600);
                    }
                    showToast("发料成功", true);

                    if (StringUtils.equals(actionType, "VERIFY_APPOINTMENT_MLOT")) {
                        //后台检验成功就把物料批加入到待发料的集合中
                        mLotOutAdapter.addData(getText(etMLotID));
                        MyUtils.clearTextInTextView(etMLotID);
                        // 物料扫描框获取焦点，避免因扫描头问题造成焦点错乱
                        etMLotID.requestFocus();
                    } else {
                        // 更新该领料单已经发料了的数量 对应 PickingEntity的reserved6字段
                        tvReserved6.setText(pickingEntity.getRESERVED6());
                        // 清空适配器里面已经发料了的物料批信息
                        MyUtils.clearDataInAdapter(mLotOutAdapter);
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<PickingEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "PICKAPPOINTMENT");
            }
        };

        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", actionType);
        map.addProperty("MATERIALTYPE", "RLF");

        // 领料单信息提交到后台
        final ArrayList<PickingEntity> pickingEntities = new ArrayList<>(1);
        PickingEntity pickingEntity = new PickingEntity();
        pickingEntity.setOBJECTRRN(appointmentObjectRrn);
        pickingEntities.add(pickingEntity);
        map.add("APPOINTMENTTOOLLIST", new JsonParser().parse(new Gson().toJson(pickingEntities)).getAsJsonArray());

        // 提交物料批号信息时，验证与发料生成JSON方式有所不同
        // 验证：直接从物料输入框中获取
        // 发料：从发料adapter里面获取
        switch (actionType) {
            case "VERIFY_APPOINTMENT_MLOT":

                final List<String> mLotList = new ArrayList<>(1);
                mLotList.add(getText(etMLotID));

                map.add("MLOTLIST", new JsonParser().parse(new Gson().toJson(mLotList)).getAsJsonArray());
                break;

            case "APPOINTMENT_MLOT_OUT":
                map.add("MLOTLIST", new JsonParser().parse(new Gson().toJson(mLotOutAdapter.getData())).getAsJsonArray());
                break;

        }

        NetUtils.requestPostNet("IF.PICKAPPOINTMENT", "Common", MaterialRlfOutActivity.this, map, callBack);
    }

}

// 框架发料单数据适配器
class MLotRlfOutAdapter extends BaseQuickAdapter<String, BaseViewHolder> {

    public MLotRlfOutAdapter(@Nullable List<String> data) {
        super(R.layout.adapter_lot_shelves, data);
    }

    @Override
    protected void convert(BaseViewHolder helper, String item) {
        // 以下栏位取消不要
        helper.setGone(R.id.tvCircuit,false);

        //数据转换
        helper.setText(R.id.tvLot,String.valueOf(helper.getAdapterPosition() + 1));
        helper.setText(R.id.tvLineID, item);

        // 为移除框注册移除事件
        helper.getView(R.id.ivDelete).setOnClickListener(view -> remove(helper.getAdapterPosition()));

    }

}
